package com.dkm.ou.me.domain;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.core.util.string.StringUtils;
import com.dkm.biz.domain.AbstractDomain;
import com.dkm.ou.me.persistence.dao.ResGrantDao;
import com.dkm.ou.me.persistence.dao.ResGrantQueryDao;
import com.dkm.ou.me.persistence.dao.RoleDao;
import com.dkm.ou.me.persistence.entity.ResGrantPo;
import com.dkm.ou.me.persistence.entity.RolePo;

/**
 * 对象功能:角色 领域对象实体
 * 开发公司:SKG.COM
 * 开发人员:颜超敏
 * 创建时间:2014-12-12 11:01:12
 */
@Service
@Scope("prototype")
public class Role extends AbstractDomain<String, RolePo>{
	 
	 private RoleDao roleDao = null;
	 
	 private ResGrantDao resGrantDao = null;
	 
	 private ResGrantQueryDao resGrantQueryDao = null;

	protected void init(){
		roleDao = SpringHelper.getBean(RoleDao.class);
		resGrantDao = SpringHelper.getBean(ResGrantDao.class);
		resGrantQueryDao = SpringHelper.getBean(ResGrantQueryDao.class);
		setDao(roleDao);
	}

	public void save(Role role) {
		//是否新增
		boolean isNew = StringUtils.isEmpty(role.getId())?true:false;
		Map<String, String> 	resGrantMap=new HashMap<String, String>();
		RolePo rolePo=role.getData();
		if(!isNew){
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("whereSql", "role_id_='"+role.getId()+"'");
			params.put("roleId", role.getId());
			List<ResGrantPo> resGrantPos=	resGrantQueryDao.findAll(params);
			if(resGrantPos!=null){
				for(ResGrantPo resGrantPo:resGrantPos){
					resGrantMap.put(resGrantPo.getResId(), resGrantPo.getStatus());
				}
			}
			resGrantDao.deleteByKey("deleteByRoleId",params);
			role.update();
		}else{
			role.create();
		}
		String resIds=rolePo.getResIds();
		if(resIds!=null&&!"".equals(resIds)){
			String[] ids=resIds.split(";");
			for(String resId:ids){
				ResGrantPo resGrantPo=new ResGrantPo();
				resGrantPo.setId(getIdGenerator().genSid());
				resGrantPo.setResId(resId);
				resGrantPo.setRoleId(rolePo.getId());
				String status=resGrantMap.get(resId)==null?"draft":resGrantMap.get(resId);
				resGrantPo.setStatus("active");
				resGrantDao.create(resGrantPo);
			}
		}
		
		
	}	 
	 
}
